// const TesseractCore = require('tesseract.js-core');
const Tesseract = require('tesseract.js/dist/tesseract.min.js');

// httpClient.js - HTTP请求封装
class HttpClient {
    constructor(baseUrl = '') {
        this.baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
    }

    async request(method, endpoint, data = {}, headers = {}) {
        const url = `${this.baseUrl}/${endpoint}`
        const config = {
            method,
            headers: {
                'Content-Type': 'application/json'
            }
        }

        if (method === 'GET') {

        } else {
            config.body = JSON.stringify(data)
        }

        try {
            const response = await fetch(url, config)
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`)
            }
            return await response.json()
        } catch (error) {
            console.error(`Request failed: ${error}`)
            throw error
        }
    }

    async get(endpoint, params = {}, headers = {}) {
        return this.request('GET', endpoint, params, headers)
    }

    async post(endpoint, data = {}, headers = {}) {
        return this.request('POST', endpoint, data, headers)
    }
}


// wechatAutomation.js - 主逻辑
export default class WeChatAutomation {
    constructor(ip, keywords, loopCount, logCallback) {
        this.httpClient = new HttpClient(`http://${ip}:18080/api`)
        this.keywords = Array.isArray(keywords) ? keywords : [keywords]
        this.loopCount = loopCount
        this.logCallback = logCallback
        this.maxCalls = 50
        this.allUsers = []
        this.callCount = 0 // 跟踪实际调用次数
        this.ip = ip
    }

    async sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms))
    }

    async click(x, y) {
        const data = {x, y}
        return this.httpClient.post('click', data)
    }

    async inputText(value) {
        return this.httpClient.post('inputText', {value})
    }

    async swipe(x1, y1, x2, y2, duration = 500) {
        const data = {x1, y1, x2, y2, duration}
        return this.httpClient.post('swipe', data)
    }

    async screenShot() {
        return this.httpClient.get('screenShotBase64')
    }

    async startPackage(packageName) {
        return this.httpClient.get('startPackage?packageName=' + packageName, {})
    }

    async stopPackage(packageName) {
        return this.httpClient.get('stopPackage?packageName=' + packageName, {})
    }

    async init() {
        try {
            // 关闭微信
            try {
                const stopResponse = await this.stopPackage('com.tencent.mm')
                if (stopResponse.code !== 1) {
                    const item = {
                        ip: this.ip,
                        message: "ADB服务连接异常"
                    }
                    this.logCallback(1, item)
                }else{
                      const item = {
                        ip: this.ip,
                        message: "ADB服务连接成功"
                    }
                    this.logCallback(2, item)
                }
            } catch (error) {
                const item = {
                    ip: this.ip,
                    message: "ADB服务连接异常"
                }

                this.logCallback(1, item)
            }


            await this.sleep(5000)

            // 启动微信
            const startResponse = await this.startPackage('com.tencent.mm')
            if (startResponse.code !== 1) {
                throw new Error('Failed to start WeChat')
            }

            await this.sleep(6000)

            // 打开发现页
            await this.click(680, 2190)
            await this.sleep(5000)

            // 打开视频号
            await this.click(1, 485)

            // 开始处理关键词
            await this.processKeywords()
        } catch (error) {
            this.logCallback(0, `初始化失败: ${error.message}`)
            throw error
        }
    }

    async processKeywords(keywordIndex = 0) {
        if (keywordIndex >= this.keywords.length) {
            await this.saveToExcel()
            return
        }

        const keyword = this.keywords[keywordIndex]
        this.logCallback(0, `开始处理关键词: ${keyword}`)

        try {
            // 打开视频号搜索
            await this.click(890, 175)
            await this.sleep(4000)

            // 输入关键词
            await this.inputText(keyword)
            await this.sleep(4000)

            // 点击搜索
            await this.click(900, 165)
            await this.sleep(7000)

            // 筛选
            await this.click(980, 300)
            await this.sleep(2000)

            // 点击最新
            await this.click(810, 440)
            await this.sleep(4000)

            // 点击第一个item
            await this.click(300, 755)

            // 处理用户
            await this.processUsers(keyword)

            // 返回
            await this.click(55, 160)

            // 处理下一个关键词
            await this.processKeywords(keywordIndex + 1)
        } catch (error) {
            this.logCallback(0, `处理关键词 ${keyword} 时出错: ${error.message}`)
        }
    }

    extractAllContacts(text) {
        // 1. 匹配手机号（1开头，11位数字）
        const phoneRegex = /(1[3-9]\d{9})/g;
        const phones = text.match(phoneRegex) || [];

        // 2. 匹配微信号（支持多种前缀写法）
        const wechatRegex = /(?:微信|wechat|wx|微信号|\+[vV](?:x)?|vx|VX)[：:\s]*([a-zA-Z][a-zA-Z0-9_-]{5,19})/gi;
        const wechats = [...text.matchAll(wechatRegex)].map(match => match[1]) || [];

        // 3. 合并结果并去重
        const allContacts = [...new Set([...phones, ...wechats])];

        return allContacts;
    }

    async processUsers(keyword) {
        for (let i = 0; i < this.loopCount; i++) {
            if (this.callCount >= this.maxCalls) {
                this.logCallback(0, '已达到最大私信发送次数')
                break
            }

            this.logCallback(0, `处理第 ${i + 1} 个用户，关键词: ${keyword}`)

            try {
                // 每5个检查是否最后一个
                // if ((i + 1) % 5 === 0) {
                //   const isLast = await this.checkIfLastUser()
                //   if (isLast) break
                // }

                await this.sleep(4000)

                // 点击用户详情
                await this.click(210, 2135)
                await this.sleep(3000)

                // 截图处理
                const screenshot = await this.screenShot()
                let _this = this
                //通过本地python服务识别
                fetch('http://127.0.0.1:39800/ocr', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({base64: screenshot.data})
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log('OCR Result:', data.result)
                        const content = data.result.join(",")
                        const item = {
                            device: this.ip,
                            type: 0,
                            keyword: keyword,
                            content: content,
                            info: _this.extractAllContacts(content).join(",")
                        }
                        this.logCallback(0, item)

                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });

                await this.sleep(5000)

                // 关闭用户详情
                await this.click(560, 380)
                await this.sleep(3000)

                // 滑动到下一个
                await this.swipe(0.2, 800, 0.2, 100)
            } catch (error) {
                this.logCallback(0, `处理用户时出错: ${error.message}`)
            }
        }
    }


    async checkIfLastUser() {
        try {
            const screenshot = await this.screenShot()
            // 这里需要实现OCR检查逻辑
            // const isLast = userNameOcr(screenshot.data, this.ocrEngine)
            const isLast = false // 临时占位

            if (isLast) {
                this.logCallback(0, '已到最后一个用户')
                await this.click(55, 160)
                return true
            }
            return false
        } catch (error) {
            this.logCallback(0, `检查最后一个用户时出错: ${error.message}`)
            return false
        }
    }

    async saveUserInfo(screenshot, keyword) {
        try {
            // 这里需要实现OCR保存用户信息逻辑
            // const userInfo = await imgOcr(screenshot.data, keyword)
            // this.allUsers.push(userInfo)
        } catch (error) {
            this.logCallback(0, `保存用户信息失败: ${error.message}`)
            throw error
        }
    }

    async saveToExcel() {
        if (this.allUsers.length === 0) {
            this.logCallback(0, '没有找到用户数据')
            return
        }

        try {
            // 这里需要实现Excel导出逻辑
            // 示例使用 xlsx 库:
            // import * as XLSX from 'xlsx'
            // const worksheet = XLSX.utils.json_to_sheet(this.allUsers)
            // const workbook = XLSX.utils.book_new()
            // XLSX.utils.book_append_sheet(workbook, worksheet, "Users")
            // XLSX.writeFile(workbook, `微信视频号_${this.keywords.join('_')}.xlsx`)

            const filename = `微信视频号_${this.keywords.join('_')}.xlsx`
            this.logCallback(0, `所有用户数据已保存到 ${filename}`)
        } catch (error) {
            this.logCallback(0, `保存Excel文件时出错: ${error.message}`)
            throw error
        }
    }
}

// 使用示例
// const automation = new WeChatAutomation(
//   '10.88.80.176',
//   ['关键词1', '关键词2'],
//   10,
//   new OCREngine(),
//   ['私信内容1', '私信内容2'],
//   true,
//   message => console.log(message)
// )
//
// automation.init().catch(console.error)
